package com.stu.day08.equals;

import java.util.HashSet;
import java.util.Objects;

/**
 * HashSet无序不可重复(通过HashCode()初步判断,equals()再次判断)
 * @author zy
 * @date 2025/1/29 17:11
 */
public class HashCodeDemo {
    public static void main(String[] args) {
        User u1 = new User(1,"aa");
        User u2 = new User(2,"bb");
        User u3 = new User(3,"cc");
        User u4 = new User(1,"dd");

        HashSet<User> set = new HashSet<>();  //
        set.add(u1);
        set.add(u2);
        set.add(u3);
        set.add(u4);
        for (User u : set) {
            System.out.println(u);
        }
    }
}
class User{
    private int id;
    private String name;
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("User{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
//        return id == user.id;
        return id == user.id && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {  // 通过id计算出hash值
        return Objects.hashCode(id);
    }
}
